package com.wtzz.police.base.service.impl;

import com.wtzz.police.base.bean.dto.DepartmentDto;
import com.wtzz.police.base.bean.dto.DepartmentInfoDto;
import com.wtzz.police.base.entity.Department;
import com.wtzz.police.base.repository.base.BaseRepository;
import com.wtzz.police.base.util.RepoHelper;
import com.wtzz.police.base.repository.DepartmentRepository;
import com.wtzz.police.base.service.base.BaseCurdServiceImpl;
import com.wtzz.police.base.service.DepartmentService;
import com.wtzz.police.base.util.component.MapperWrapper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigInteger;
import java.util.List;

/**
 * 类说明
 *
 */
@Service
@Slf4j
@Transactional
public class DepartmentServiceImpl extends BaseCurdServiceImpl<Department, String> implements DepartmentService, RepoHelper {

    @Autowired
    private DepartmentRepository repo;

    @Override
    protected BaseRepository<Department, String> getRepository() {
        return repo;
    }


    @Override
    public Page<DepartmentInfoDto> listNotDeleted(Pageable pageable) {
        String innerSql = "select id,code,name,fullname,enable from gs_department where deleted=0";
        BigInteger total = (BigInteger) em.createNativeQuery(wrapSelectCount(innerSql, "data")).getSingleResult();
        List list = em.createNativeQuery(innerSql)
                      .setMaxResults(pageable.getPageSize())
                      .setFirstResult(pageable.getPageNumber() * pageable.getPageSize())
                      .unwrap(NativeQuery.class)
                      .setResultTransformer(Transformers.aliasToBean(DepartmentInfoDto.class))
                      .getResultList();
        return new PageImpl<DepartmentInfoDto>(list, pageable, total.longValue());
    }

    @Override
    public List<DepartmentInfoDto> listAllNotDeleted() {
        String innerSql = "select id,code,name,fullname,enable from gs_department where deleted=0";
        List list = em.createNativeQuery(innerSql)
                      .unwrap(NativeQuery.class)
                      .setResultTransformer(Transformers.aliasToBean(DepartmentInfoDto.class))
                      .getResultList();
        return list;
    }

    @Override
    public DepartmentInfoDto findByIdNotDeleted(String id) {
        Department department = findNotDeleted(id);
        return mapper.map(department, DepartmentInfoDto.class);
    }

}
